/*
https://leetcode-cn.com/problems/cracking-the-safe/solution/yi-bu-yi-bu-tui-dao-chu-0ms-jie-fa-tan-xin-gou-zao/
 */
import java.util.HashMap;
import java.util.Map;

public class Solution753 {
    public String crackSafe(int n, int k) {
        StringBuilder s=new StringBuilder();
        if (n==1){
            for (int i = 0; i < k; i++) {
                s.append(i);
            }
        }else{
            for (int i=0;i<n-1;i++){
                s.append(0);
            }
            String cur=s.toString();
            Map<String,boolean[]> map=new HashMap<>();
            while (true){
                map.putIfAbsent(cur,new boolean[k]);
                int target=-1;
                for (int i=k-1;i>=0;i--){
                    if (!map.get(cur)[i]){
                        target=i;
                        break;
                    }
                }
                if (target==-1){
                    break;
                }
                s.append(target);
                map.get(cur)[target]=true;
                cur=cur.substring(1).concat(String.valueOf(target));
            }
        }
        return s.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution753().crackSafe(2,2));
    }
}
